package org.snail.proxy;

import net.bytebuddy.implementation.bind.annotation.AllArguments;
import net.bytebuddy.implementation.bind.annotation.Origin;
import net.bytebuddy.implementation.bind.annotation.RuntimeType;
import org.snail.SnailClient;
import org.snail.transport.protocol.Request;

import java.lang.reflect.Method;

/**
 * 调用代理触发类
 *
 * Created by fish on 17/8/28.
 */
public class ProxyAsyncHandler {


    private SnailClient client;

    public ProxyAsyncHandler(SnailClient client){
        this.client = client;

    }


    @RuntimeType
    public Object invoke(@Origin Method method, @AllArguments @RuntimeType Object[] args){
        Class<?> clazz = method.getReturnType();
        Request request = new Request();
        request.setMethodName(method.getName());
        request.setReturnType(method.getReturnType());
        request.setArgs(args);
        client.getDispatcher().invoke(null,request,0);
        return defaultValue(clazz);
    }


    /**
     * 获取默认返回值
     *
     * @param clazz
     */
    private Object defaultValue(Class<?> clazz){
        if (clazz.isPrimitive()) {
            if (clazz == byte.class) {
                return (byte) 0;
            }
            if (clazz == short.class) {
                return (short) 0;
            }
            if (clazz == int.class) {
                return 0;
            }
            if (clazz == long.class) {
                return 0L;
            }
            if (clazz == float.class) {
                return 0F;
            }
            if (clazz == double.class) {
                return 0D;
            }
            if (clazz == char.class) {
                return (char) 0;
            }
            if (clazz == boolean.class) {
                return false;
            }
        }
        return null;
    }


}
